<?php

class FacturaController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Factura;

        $this->performAjaxValidation($model, 'factura-form');

        if (isset($_POST['Factura'])) {
            $model->attributes = $_POST['Factura'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        $this->performAjaxValidation($model, 'factura-form');

        if (isset($_POST['Factura'])) {
            $model->attributes = $_POST['Factura'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Factura');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Factura('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Factura']))
            $model->attributes = $_GET['Factura'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Factura::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'factura-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionHistorialFacturas() {
//        $this->admin = true;
        $model = new Factura('search');
          $model->fechas = date('01/m/Y') . ' - ' . Util::obtenerUltimoDiaMes() . date("/m/Y");
        $model->unsetAttributes();
        if (isset($_GET['search'])) {
            if (!empty($_GET['search']['value'])) {
                $n = explode(' - ', $_GET['search']['value']);
                $model->date_first = $n['0'];
                $model->date_last = $n['1'];
            }
        }
        $this->render('historial', array(
            'model' => $model,
        ));
    }
    
       

    public function actionExportarHistorial($venta_id = null, $fechas = null) {
        $datos = array();
        $facturas = array();
        $model = new Factura('search');
        $model->unsetAttributes(); // clear any default values
        //para generar excel desde historial_por_entidad
//        die();
        if ($_POST['Factura'] == 'todos') {
            if ($fechas != null || $fechas != '') {
                $fechas = explode(' - ', $fechas);
                $model->date_first = $fechas[0];
                $model->date_last = $fechas[1];
                $facturas = $model->rango($model->date_first, $model->date_last);
//                 var_dump($facturas);
            }
           
            $facturas = $facturas->findAll();
//             var_dump($facturas);
//            die();
//            die();
        } else {

//            Coloca en $data solo los id de los formularios  seleccionadas
            $registros = explode(',', $_POST['Factura']);
            foreach ($registros as $registro_id) {
                $datos = $model->findByPk($registro_id);


                array_push($facturas, $datos);
            }
        }

//        $grid = $model->obtenerPreguntas($idformulario);
//        $preguntas = $model->obtenerPreguntas($idformulario);
//         var_dump($preguntas);
//            die();
        if (!empty($facturas)) {
            $objExcel = new PHPExcel();
            $objExcel->setActiveSheetIndex(0) // Titulo del reporte
                    ->setCellValue('A1', 'Numero Factura')  //Titulo de las columnas
                    ->setCellValue('B1', 'Persona')  //Titulo de las columnas
                    ->setCellValue('C1', 'Cédula')  //Titulo de las columnas
                    ->setCellValue('D1', 'Correo')  //Titulo de las columnas
                    ->setCellValue('E1', 'Fecha Pedido')
                    ->setCellValue('F1', 'Valor')

            ;
            //Devuelve la ultima columna utilizada en este caso la F
//            $lastColumn = $objExcel->getActiveSheet()->getHighestColumn();
//            $lastTitles = $lastColumn;
//            foreach ($grid as $col) {
//                //va iterando desde la E,F,G...n en la fila 1 ($head)
//                $lastTitles++;
//                $objExcel->setActiveSheetIndex(0)->setCellValue($lastTitles . '1', $col['label']);
//            }
            $id = 2;
            foreach ($facturas as $data) {
//                $factura = Factura::model()->findAllByPk($data);
//                foreach ($data as $value) {
//                    $user = Yii::app()->user->um->loadUserById($value->usuario_creacion_id)->username;
                    $objExcel->setActiveSheetIndex(0)
                            ->setCellValue('A' . $id, $data->numero)
                            ->setCellValue('B' . $id, $data->persona->nombres)  //Titulo de las columnas
                            ->setCellValue('C' . $id, $data->persona->cedula)  //Titulo de las columnas
                            ->setCellValue('D' . $id, $data->persona->correo)  //Titulo de las columnas
                            ->setCellValue('E' . $id, $data->pedido->fecha)  //Titulo de las columnas
                            ->setCellValue('F' . $id, $data->pedido->valor_total)
//                            ->setCellValue('D' . $id, $value->motivo->nombre)
                    ;
                    $id++;
//                }
            }

            $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_HAIR,
                        'color' => array('argb' => '000000'),
                    ),
                ),
            );
            
             for ($i = 'A'; $i <= 'F'; $i++) {
            $objExcel->setActiveSheetIndex(0)->getColumnDimension($i)->setAutoSize(TRUE);
        }
//            $objExcel->getActiveSheet()->getStyle('A1:' . $lastContent . --$id)->applyFromArray($styleArray);

            $objExcel->getActiveSheet()->setTitle('Reporte Facturas');
//       Se activa la hoja para que sea la que se muestre cuando el archivo se abre
            $objExcel->setActiveSheetIndex(0);
//            for ($i = 'A'; $i <= $lastContent; $i++) {
//                $objExcel->setActiveSheetIndex(0)->getColumnDimension($i)->setAutoSize(TRUE);
//            }
////// Inmovilizar paneles
            $objExcel->getActiveSheet(0)->freezePaneByColumnAndRow(1, 2);
//        // Se manda el archivo al navegador web, con el nombre que se indica, en formato 2007
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Reporte Facturas.xlsx"');
            header('Cache-Control: max-age=0');

            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }
    
    

}
